import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-09-17
 * Time: 23:59
 */

/**
 * 多数元素
 */
public class MajorityElement {

    public int majorityElement(int[] nums) {
        Map<Integer, Integer> hash = new HashMap<>();
        int n = nums.length / 2;
        for(int x : nums){
            hash.put(x,hash.getOrDefault(x,0) + 1);
        }

        Iterator iter = hash.entrySet().iterator();
        while (iter.hasNext()) {

            Map.Entry entry = (Map.Entry)iter.next();

            //获得entry对象的key和val并比较
            Integer key = (Integer) entry.getKey();
            if (hash.getOrDefault(key, 0) > n) {
                return key;
            }
        }

        return -1;
    }
}
